import axios from "axios";
import store from "@/store";
import { getStorageToken, removeStorageToken } from '@/utils/auth'

const service = axios.create({
	baseURL: window.config.VUE_APP_BASE_API, // url = base url + request url
	withCredentials: true,
	responseType: "blob"
});
service.interceptors.request.use(
	config => {
		if(store.getters.token) {
			config.headers["Content-Type"] = "application/json;charset=UTF-8";
			config.headers["token"] = getStorageToken();
			config.headers['Authorization'] = 'Bearer ' + getStorageToken();
		}
		return config;
	},
	error => Promise.reject(error)
);

service.interceptors.response.use(response => {
	const blob = new Blob([response.data]);
	const name = headerName(response);
	download(blob, name);
	return response;
});

function headerName(response) {
	const disposition = response.headers["content-disposition"];
	if(disposition) {
		return decodeURI(disposition.slice(disposition.lastIndexOf("filename") + 9).trim())
	} else {
		return "导出.xlsx"
	}
}

function download(blob, name) {
	const linkNode = document.createElement("a");
	linkNode.style.display = "none";
	linkNode.href = URL.createObjectURL(blob);
	linkNode.download = name;
	document.body.appendChild(linkNode);
	linkNode.click();
	URL.revokeObjectURL(linkNode.href);
	document.body.removeChild(linkNode);
}

export default service;